import React, { memo, useRef, FC } from 'react';
import { FormInstance } from 'antd/lib/form';
// import styles from './index.less';
import CommonModal from '@/components/CommonModal';
import AddForm from './AddForm';
import { modelName } from '../../../../index';
import useHoxModel from '../../../../useHoxModel';
import { AddDoorGroupType, EditDoorGroupType } from '../../../../API';

interface Props {}

const ModalContent: FC<Props> = () => {
  const { addDoorGroup, editDoorGroup, getDoorGroupList, doorGroupInfo } = useHoxModel((model) => [
    model.doorGroupInfo,
  ]);
  const formRef = useRef<FormInstance>();

  const confim = async <T extends {}>(
    cancel: () => void,
    request: (params: T) => Promise<any>,
    filterData?: (props: any) => Promise<any>,
  ) => {
    try {
      const fields: any = await formRef.current?.validateFields();
      const params = await (filterData ? filterData(fields) : fields);

      let res = await request(params);
      if (!(res.result < 0)) {
        getDoorGroupList();
        cancel();
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  return (
    <>
      <CommonModal
        title="门组编辑"
        width={600}
        type={modelName + 'door-group-edit'}
        onOk={async (cancelModal: (type?: string, clear?: boolean) => void) => {
          const filterData = (fields: any) => {
            return {
              ...fields,
              id: doorGroupInfo?.id,
            };
          };
          await confim<EditDoorGroupType>(cancelModal, editDoorGroup, filterData);
        }}
      >
        <AddForm formRef={formRef} />
      </CommonModal>
      <CommonModal
        title="门组新增"
        width={600}
        type={modelName + 'door-group-add'}
        onOk={async (cancelModal: (type?: string, clear?: boolean) => void) => {
          await confim<AddDoorGroupType>(cancelModal, addDoorGroup);
        }}
      >
        <AddForm formRef={formRef} />
      </CommonModal>
    </>
  );
};

export default memo(ModalContent);
